package controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.jfinal.core.Controller;
import com.jfinal.core.NotAction;
import com.jfinal.core.Path;
import common.model.User;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import service.DbRealmService;
import service.UserService;

import java.io.File;
import java.util.List;
import java.util.Map;

@Path(value = "/admin/user", viewPath = "/pages")
@RequiresAuthentication
public class UserController extends Controller {

    UserService userService=new UserService();

    public void index(){
        render("user-list.html");
    }

    public void add(){
        User user=getModel(User.class,"user");
        user.setRole("user");
        user.setPassword("123456");
        if(isOnly(user.getEmail())){
            userService.addData(user);
            renderJson("erro",0);
            return;
        }
        renderJson("erro",1);
    }

    public void list(){
        int page=getInt("page");
        int size=getInt("limit");
        setAttr("datas",userService.getDatasByPage(page,size));
        setAttr("erro",0);
        renderJson();
    }

    public void repass(){
        String id=get("id");
        userService.updateData(userService.getDataById(id).setPassword("123456"));
        renderJson("erro",0);
    }

    public void del(){
        String id=get("id");
        userService.deleteDataById(id);
        renderJson("erro",0);
    }

    public void upload(){
        File file=getFile().getFile();
        setAttr("erro",0);
        set("msg",userService.importFromFile(file));
        renderJson();
    }

    public void edt(){
        User user=getModel(User.class,"user");
        userService.updateData(user);
        setAttr("erro",0);
        renderJson();
    }

    @NotAction
    public boolean isOnly(String email){
        return userService.getByEmail(email)==null;
    }
}
